package com.system.email.email;

import com.redis.RedisUtil;
import com.system.email.InformSend;
import com.system.email.properties.EmailProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.concurrent.CountDownLatch;

/**
 * @Author hewei
 * @Description //TODO  消息通知发送实现类（邮件发送）
 * @Date 2021/6/22
 **/
@Slf4j
@Component
public class EmailInformSend  implements InformSend {

    private final EmailProperties emailProperties;

    private final CountDownLatch countDownLatch;


    private final RedisUtil redisUtil;


    public EmailInformSend(EmailProperties emailProperties, CountDownLatch countDownLatch, RedisUtil redisUtil) {
        this.emailProperties = emailProperties;
        this.countDownLatch = countDownLatch;
        this.redisUtil = redisUtil;
    }


    /**
     *  发送邮件
     * @param emailMessage 短信接受对象
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void send(EmailMessage emailMessage){
        try{
            // 使用环境属性和授权信息，创建邮件会话
            Session instance = Session.getInstance(getProperties(), getAuthenticator());
            //创建邮件消息
            MimeMessage message = new MimeMessage(instance);
            //发件邮箱
            InternetAddress form = new InternetAddress(emailProperties.getAccount());
            message.setFrom(form);
            // 设置收件人
            message.setRecipients(RecipientType.TO, emailMessage.getEmailAddress());  //支持群发，多地址用逗号分隔
            // 设置邮件标题
            message.setSubject(emailProperties.getSubject());
            // 设置邮件的内容体
            String code = getCode();
            message.setContent(emailMessage.getContent()+code+" 有效时间5分钟之内", emailMessage.getContentType());
            // 发送邮件
            Transport.send(message);
            log.info("emailType:{}", emailMessage.getEmailType());
            redisUtil.set(emailMessage.getEmailType(), code, 60 * 5);
            log.info("邮件发送结束");
        }catch(Exception e){
            log.error("发送邮件出现异常！"+e.getMessage());
            e.printStackTrace();
            throw new RuntimeException("发送邮件出现异常！"+e.getMessage());
        }
        countDownLatch.countDown();
    }

    /**
     *  构建 Properties 对象
     * @return
     */
    public Properties getProperties(){
        Properties properties = new Properties();
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.host", "smtp.qq.com");
        // 发件人的账号
        properties.put("mail.user", "1072484187@qq.com");
        //发件人的密码
        properties.put("mail.password", "ktkuaskbmghibajj");
        properties.put("mail.smtp.socketFactory.port", "465");
        properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.port", "465");
        return properties;
    }

    /**
     *  构建 Authenticator 认证对象
     * @return
     */
    public Authenticator getAuthenticator(){
        /**
         * 构建授权信息，用于进行SMTP进行身份验证
         */
        return new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                /**
                 *  使用 账号 授权码 获取认证对象
                 */
                return new PasswordAuthentication(emailProperties.getAccount(), emailProperties.getAuthCode());
            }
        };
    }

    /**
     * 获取验证码
     * @return
     */
    public String getCode(){
        Random random = new Random();
        String result="";
        for (int i=0;i<6;i++)
        {
            result+=random.nextInt(9);
        }
        return result;
    }
}
